import React, { useState, useCallback } from 'react';
import { 
  Video, 
  Upload, 
  Download, 
  Settings, 
  Play,
  FileText,
  Clock,
  HardDrive,
  X
} from 'lucide-react';
import { invoke } from '@tauri-apps/api/core';
import { VideoFile } from '@/types/video';
import FileUploader from '@/components/common/FileUploader';
import { formatFileSize } from '@/utils/format';
import './styles.less';

interface FormatConverterProps {
  className?: string;
}

export const FormatConverter: React.FC<FormatConverterProps> = ({ className = '' }) => {
  const [selectedFiles, setSelectedFiles] = useState<VideoFile[]>([]);
  const [outputFormat, setOutputFormat] = useState('mp4');
  const [quality, setQuality] = useState('medium');
  const [isConverting, setIsConverting] = useState(false);
  const [conversionProgress, setConversionProgress] = useState(0);

  // 支持的输出格式
  const supportedFormats = [
    { value: 'mp4', label: 'MP4', description: '最常用的视频格式，兼容性好' },
    { value: 'avi', label: 'AVI', description: '支持高质量视频，文件较大' },
    { value: 'mov', label: 'MOV', description: 'Apple QuickTime格式，适合编辑' },
    { value: 'mkv', label: 'MKV', description: '开源格式，支持多种编码' },
    { value: 'wmv', label: 'WMV', description: 'Windows Media格式' },
    { value: 'webm', label: 'WebM', description: 'Web优化格式' },
  ];

  // 质量预设
  const qualityPresets = [
    { value: 'low', label: '低质量', description: '文件最小，适合移动设备' },
    { value: 'medium', label: '标准质量', description: '平衡文件大小和质量' },
    { value: 'high', label: '高质量', description: '高质量保存，文件较大' },
    { value: 'lossless', label: '无损', description: '最高质量，文件最大' },
  ];

  const handleFileSelect = useCallback((files: File[]) => {
    const videoFiles: VideoFile[] = files.map((file, index) => ({
      id: `file-${index}-${Date.now()}`,
      name: file.name,
      path: file.name,
      format: file.name.split('.').pop() || '',
      size: file.size,
      duration: 0,
      createdAt: new Date().toISOString(),
    }));
    setSelectedFiles(videoFiles);
  }, []);

  const handleRemoveFile = useCallback((fileId: string) => {
    setSelectedFiles(prev => prev.filter(file => file.id !== fileId));
  }, []);

  const handleConvert = useCallback(async () => {
    if (selectedFiles.length === 0) return;

    setIsConverting(true);
    setConversionProgress(0);

    try {
      // 实际转换过程
      for (let i = 0; i < selectedFiles.length; i++) {
        const file = selectedFiles[i];
        
        // 模拟进度更新（实际实现中会监听Tauri后端进度）
        for (let progress = 0; progress <= 100; progress += 10) {
          await new Promise(resolve => setTimeout(resolve, 300));
          setConversionProgress(progress);
        }

        // 调用Tauri后端进行转换
        try {
          const result = await invoke('convert_video', {
            inputPath: file.path,
            outputFormat: outputFormat,
            quality: quality,
          });
          console.log(`文件 ${file.name} 转换成功:`, result);
        } catch (error) {
          console.error(`文件 ${file.name} 转换失败:`, error);
          throw error;
        }
      }

      // 转换完成
      setIsConverting(false);
      setConversionProgress(100);
      
      // 显示成功消息
      console.log(`成功转换 ${selectedFiles.length} 个文件`);
      
      // 在实际实现中，这里会显示成功提示
      // dispatch(showToast({ type: 'success', title: '转换完成', message: `成功转换 ${selectedFiles.length} 个文件` }));
    } catch (error) {
      console.error('转换失败:', error);
      setIsConverting(false);
      
      // 在实际实现中，这里会显示错误提示
      // dispatch(showToast({ type: 'error', title: '转换失败', message: '请检查文件格式和参数设置' }));
    }
  }, [selectedFiles, outputFormat, quality]);


  return (
    <div className={`format-converter ${className}`}>
      {/* 页面标题 */}
      <div className='format-converter__header'>
        <div className='format-converter__title-section'>
          <Video className='format-converter__title-icon' />
          <div>
            <h1 className='format-converter__title'>格式转换</h1>
            <p className='format-converter__description'>
              将视频文件转换为不同格式，支持主流的视频格式转换
            </p>
          </div>
        </div>
      </div>

      <div className='format-converter__content'>
        {/* 文件上传区域 */}
        <div className='format-converter__upload-section'>
          <div className='format-converter__upload-card'>
            <div className='format-converter__upload-header'>
              <Upload className='format-converter__upload-icon' />
              <h3>选择视频文件</h3>
              <p>支持 MP4, AVI, MOV, MKV, WMV 等格式</p>
            </div>
            
            <div className='format-converter__upload-area'>
              <FileUploader
                maxFiles={10}
                accept=".mp4,.avi,.mov,.mkv,.wmv,.flv,.webm"
                onFilesSelected={handleFileSelect}
              />
            </div>
          </div>
        </div>

        {/* 已选文件列表 */}
        {selectedFiles.length > 0 && (
          <div className='format-converter__files-section'>
            <h3 className='format-converter__files-title'>已选文件 ({selectedFiles.length})</h3>
            <div className='format-converter__files-list'>
              {selectedFiles.map((file, index) => (
                <div key={file.id} className='format-converter__file-item'>
                  <FileText className='format-converter__file-icon' />
                  <div className='format-converter__file-info'>
                    <div className='format-converter__file-name'>{file.name}</div>
                    <div className='format-converter__file-details'>
                      <span>{file.format.toUpperCase()}</span>
                      <span>{formatFileSize(file.size)}</span>
                      <span>{file.duration > 0 ? `${Math.floor(file.duration / 60)}分${file.duration % 60}秒` : '时长未知'}</span>
                    </div>
                  </div>
                  <div className='format-converter__file-actions'>
                    <button 
                      className='format-converter__remove-button'
                      onClick={() => handleRemoveFile(file.id)}
                    >
                      <X size={16} />
                    </button>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* 转换设置 */}
        <div className='format-converter__settings-section'>
          <div className='format-converter__settings-card'>
            <div className='format-converter__settings-header'>
              <Settings className='format-converter__settings-icon' />
              <h3>转换设置</h3>
            </div>

            <div className='format-converter__settings-content'>
              {/* 输出格式选择 */}
              <div className='format-converter__setting-group'>
                <label className='format-converter__setting-label'>输出格式</label>
                <div className='format-converter__formats-grid'>
                  {supportedFormats.map(format => (
                    <button
                      key={format.value}
                      className={`format-converter__format-option ${
                        outputFormat === format.value ? 'format-converter__format-option--active' : ''
                      }`}
                      onClick={() => setOutputFormat(format.value)}
                    >
                      <div className='format-converter__format-name'>{format.label}</div>
                      <div className='format-converter__format-description'>{format.description}</div>
                    </button>
                  ))}
                </div>
              </div>

              {/* 质量设置 */}
              <div className='format-converter__setting-group'>
                <label className='format-converter__setting-label'>质量预设</label>
                <div className='format-converter__quality-grid'>
                  {qualityPresets.map(preset => (
                    <button
                      key={preset.value}
                      className={`format-converter__quality-option ${
                        quality === preset.value ? 'format-converter__quality-option--active' : ''
                      }`}
                      onClick={() => setQuality(preset.value)}
                    >
                      <div className='format-converter__quality-name'>{preset.label}</div>
                      <div className='format-converter__quality-description'>{preset.description}</div>
                    </button>
                  ))}
                </div>
              </div>

              {/* 高级设置 */}
              <div className='format-converter__advanced-settings'>
                <details className='format-converter__details'>
                  <summary className='format-converter__summary'>高级设置</summary>
                  <div className='format-converter__advanced-content'>
                    <div className='format-converter__advanced-group'>
                      <label>视频编码器</label>
                      <select className='format-converter__select'>
                        <option value='h264'>H.264</option>
                        <option value='h265'>H.265</option>
                        <option value='vp9'>VP9</option>
                      </select>
                    </div>
                    <div className='format-converter__advanced-group'>
                      <label>音频编码器</label>
                      <select className='format-converter__select'>
                        <option value='aac'>AAC</option>
                        <option value='mp3'>MP3</option>
                        <option value='opus'>Opus</option>
                      </select>
                    </div>
                  </div>
                </details>
              </div>
            </div>
          </div>
        </div>

        {/* 转换按钮和进度 */}
        <div className='format-converter__action-section'>
          <div className='format-converter__action-card'>
            {isConverting ? (
              <div className='format-converter__progress-section'>
                <div className='format-converter__progress-header'>
                  <Play className='format-converter__progress-icon' />
                  <span>正在转换...</span>
                </div>
                <div className='format-converter__progress-bar'>
                  <div 
                    className='format-converter__progress-fill'
                    style={{ width: `${conversionProgress}%` }}
                  />
                </div>
                <div className='format-converter__progress-text'>
                  {conversionProgress}% 完成
                </div>
              </div>
            ) : (
              <div className='format-converter__convert-section'>
                <button
                  className='format-converter__convert-button'
                  onClick={handleConvert}
                  disabled={selectedFiles.length === 0}
                >
                  <Download className='format-converter__convert-icon' />
                  开始转换 ({selectedFiles.length} 个文件)
                </button>
                <div className='format-converter__convert-info'>
                  <div className='format-converter__info-item'>
                    <Clock className='format-converter__info-icon' />
                    <span>预计时间: {selectedFiles.length * 2} 分钟</span>
                  </div>
                  <div className='format-converter__info-item'>
                    <HardDrive className='format-converter__info-icon' />
                    <span>输出格式: {outputFormat.toUpperCase()}</span>
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};